<template>
	<view class="content">
		<view class="">
			<text>姓名：{{ detailData.name }}</text>
		</view>
		<view class="">
			<text>电话：{{ detailData.tel }}</text>
		</view>
		<button type="default" @click="remove">删除</button>
		<navigator :url="'../modify/modify?id=' + detailData._id "><button type="default">修改</button></navigator>
	</view>
</template>

<script>
	import db from '@/js_sdk/uni-clientDB/index.js';
	const dbCmd = db.command;
	let detailid;
	export default {
		data() {
			return {
				detailData: []
			};
		},
		onLoad(event) {
			// console.log("event:",event);
			detailid = event.id
			//TODO 校验detailid的合法性
			this.getDetail();
		},
		methods: {
			getDetail() {
				var that = this;
				uniCloud.callFunction({
					name: 'uni-clientDB',
					data: {
						command: db
							.collection('phonebook')
							.where({
								_id: detailid
							})
							.field({
								extra: false
							})
							.get()
					},
					success(res) {
						console.log(res.result);
						if (res.result.data.length === 0) {
							uni.showModal({
								content: '数据不存在，可能已经被删除',
								showCancel: false,
								success() {
									uni.navigateBack();
								}
							});
						} else {
							that.detailData = res.result.data[0];
							// console.log(that.detailData);
						}
					},
					fail(err) {
						console.error(err);
						uni.showModal({
							content: err.message || '服务器连接失败',
							showCancel: false
						});
					}
				});
			},
			remove() {
				var that = this;
				uni.showModal({
					content: '确认删除？',
					success: function(res) {
						if (res.confirm) {
							uniCloud.callFunction({
								name: 'uni-clientDB',
								data: {
									command: db
										.collection('phonebook')
										.doc(that.detailData._id)
										.remove()
								},
								success(res) {
									// console.log(res.result);
									//redirect方式跳转到列表页面
									uni.redirectTo({
										url: '../index/index'
									});
									uni.$emit('reloadList')
								},
								fail(err) {
									console.error(err);
									uni.showModal({
										content: err.message || '服务器连接失败',
										showCancel: false
									});
								}
							});
						}
					}
				});
			}
		}
	};
</script>

<style>
	.content {
		padding: 15px;
	}

	.content button {
		margin-bottom: 15px;
	}
</style>
